package gov.mogaha.ntis.cmm.mob.law.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.util.Log;

public class CmmMobLawFileUtil {
	
	public static void writeFile(String location, String fileName, String contents){
		File file = new File(location + fileName);
		boolean exists = file.exists();
		if (exists){
			file.deleteOnExit();
		}
		
		FileWriter fw = null;
		
		try {
			fw = new FileWriter(file);
			fw.write(contents);
			fw.flush();
		}catch(IOException e){
			Log.e("error",CmmMobLawFileUtil.class.getName() + " writeFile Error");
		}
		try {
			fw.close();
		} catch (Exception e) {
			Log.e("error",CmmMobLawFileUtil.class.getName() + " writeFile Error");
		}
		

	}
	
	// location - "data/data/패키지명/..", path - assets 폴더내의 Path, files - 복사할 파일들의 이름
	public static void chkFile(String location, String path, String[] files, Activity activity){
		
		boolean exists;
		
		for(String file: files){
			exists = (new File(location + file)).exists();
			
			if(!exists){
				copy(location, path, file, activity);
			}
		}
	}
	
	public static void copy(String location, String path, String file, Activity activity) {

		boolean exists = (new File(location + file)).exists();
		if (exists)
			return;

		File f = new File(location);
		f.mkdirs();

		InputStream is = null;
		BufferedInputStream bis = null;
		
		try {
			// 만약 assets폴더내에 폴더를 만드셧다면 .open("폴더명/"+file)로 하시면 됩니다.
			is = activity.getAssets().open(path+file);
			
			bis = new BufferedInputStream(is);
		} catch (IOException e) {
			Log.e("error",CmmMobLawFileUtil.class.getName() + " copy Error");
		}

		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		try {
			fos = new FileOutputStream(new File(location + file));
			bos = new BufferedOutputStream(fos);
		} catch (FileNotFoundException e) {
			Log.e("error",CmmMobLawFileUtil.class.getName() + " copy Error");
		}

		byte[] buffer = new byte[1024];
		int read;

		try {
			read = bis.read(buffer, 0, 1024);
			while (read != -1) {
				bos.write(buffer, 0, read);
				read = bis.read(buffer, 0, 1024);
			}
		} catch (IOException e) {
			Log.e("error",CmmMobLawFileUtil.class.getName() + " copy Error");
		}

		try {
			bos.flush();
		} catch (IOException e) {
			Log.e("error",CmmMobLawFileUtil.class.getName() + " copy Error");
		}

		try {
			bos.close();
			fos.close();			
		} catch (IOException e) {
			Log.e("error",CmmMobLawFileUtil.class.getName() + " copy Error");
		}

		try {
			is.close();
			bis.close();
		} catch (IOException e) {
			Log.e("error",CmmMobLawFileUtil.class.getName() + " copy Error");
		}
	}
}
